<script setup lang="ts">
import {
  showDialog,
  type FieldRule,
  type FormInstance,
  showSuccessToast,
  showConfirmDialog
} from 'vant'
import { watch } from 'vue'
import { ref } from 'vue'
import { patientAdd, patientUpdate, patientDel } from '@/api/user'
import type { patientAddReq } from '@/types/user'
import type { patientUpdateReq } from '@/types/user'

const emits = defineEmits<{
  (e: 'getData'): void
}>()

const mode = ref('add') // add:新增  edit:编辑
const show = ref(false)
const backEvent = () => {
  show.value = false
}
const options = [
  {
    label: '男',
    value: 1
  },
  {
    label: '女',
    value: 0
  }
]
const formData = ref<patientAddReq>({
  name: '',
  idCard: '110101198307212600',
  defaultFlag: 0, // 0 | 1
  gender: 0 // 0 | 1
})
const defaultFlag = ref(false)

/*
 watch:侦听某些数据(响应式数据)的变化 
 const stop=watch(
  需要侦听的值([需要侦听的值a,需要侦听的值b],()=>响应式数据.属性)，
  (newVal,oldVal)=>{newVal:当前值,oldVal:修改前的值},
  {
    deep:是否深度侦听
    immediate:是否立即执行回调
    flush:pre:在渲染前执行回调
          post:在渲染后执行回调
          sync:修改一次执行一次回调，渲染前执行
  }
 )
表单验证
  1:表单元素值的绑定
  2:绑定规则
  3:写规则
  4：点击确定调用form表单内的validate进行全局表单验证

*/

watch(defaultFlag, newVal => {
  formData.value.defaultFlag = newVal ? 1 : 0
})

// 表单验证
const rules: {
  name: FieldRule[]
  idCard: FieldRule[]
} = {
  name: [
    { required: true, message: '必填', trigger: 'onChange' },
    {
      pattern: /^.{2,32}$/,
      message: '请正确输入姓名',
      trigger: 'onChange'
    }
  ],
  idCard: [
    { required: true, message: '必填', trigger: 'onChange' },
    {
      pattern:
        /^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/,
      message: '请正确输入身份证号',
      trigger: 'onChange'
    }
  ]
}
const form = ref<FormInstance>()
const save = async () => {
  await form.value?.validate()
  //   if(属性不符){
  //     弹窗提示
  //   }
  const genderVal = +formData.value.idCard.slice(-2, -1) % 2
  if (genderVal !== formData.value.gender) {
    await showDialog({
      title: '提示',
      message: '您当前身份证信息与性别不符!'
    })
    return
  }
  if (mode.value === 'add') {
    await patientAdd(formData.value)
    showSuccessToast('新增成功')
  } else if (mode.value === 'edit') {
    const { name, idCard, defaultFlag, gender, id } = formData.value
    await patientUpdate({ name, idCard, defaultFlag, gender, id } as patientUpdateReq)
    showSuccessToast('编辑成功')
  }
  show.value = false
  emits('getData')
}
const closeEvent = () => {
  formData.value = {
    name: '',
    idCard: '110101198307212600',
    defaultFlag: 0, // 0 | 1
    gender: 0 // 0 | 1
  }
  defaultFlag.value = false
  setTimeout(() => {
    form.value?.resetValidation()
  }, 100)
}
// 删除点击
const delEvent = async () => {
  await showConfirmDialog({
    title: '温馨提示',
    message: '您确定删除该项吗?'
  })
  await patientDel(formData.value.id!)
  showSuccessToast('删除成功')
  show.value = false
  emits('getData')
}

defineExpose({
  show,
  formData,
  mode,
  defaultFlag
})
</script>

<template>
  <!-- :show="show" @update:show="show=$event" -->
  <div>
    <van-popup v-model:show="show" position="right" @close="closeEvent">
      <!-- 
let obj={
  a:'新增',
  b:'编辑',
  c:'草稿'
}
const mode='b'
obj[mode]===obj.b
{
  a:'新增',
  b:'编辑',
  c:'草稿'
}[mode]

      -->

      <CpNavBar
        :back="backEvent"
        :title="
          {
            add: '新增患者',
            edit: '编辑患者'
          }[mode]
        "
        rightText="保存"
        @clickRight="save"
      ></CpNavBar>
      <van-form autocomplete="off" ref="form">
        {{ formData }}
        <van-field
          :rules="rules.name"
          v-model="formData.name"
          label="真实姓名"
          placeholder="请输入真实姓名"
        />
        <van-field
          :rules="rules.idCard"
          v-model="formData.idCard"
          label="身份证号"
          placeholder="请输入身份证号"
        />
        <van-field label="性别" class="pb4">
          <!-- 单选按钮组件 -->
          <template #input>
            <cp-radio-btn v-model="formData.gender" :options="options"></cp-radio-btn>
          </template>
        </van-field>
        <van-field label="默认就诊人">
          <template #input>
            <van-checkbox v-model="defaultFlag" :icon-size="18" round />
          </template>
        </van-field>
      </van-form>
      <van-action-bar v-if="mode === 'edit'">
        <van-action-bar-button text="删除" @click="delEvent"></van-action-bar-button>
      </van-action-bar>
    </van-popup>
  </div>
</template>

<style lang="scss" scoped>
:deep() {
  .van-popup {
    width: 100vw !important;
    height: 100vh !important;
    padding-top: 46px;
    box-sizing: border-box;
  }
}
</style>
